package access

import (
	"api/config/register"
	"bytes"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
	"os"
	"os/exec"
	"sort"
	"strings"
)

func init() {
	server.Do(&server.Router{Url: "/_dev_route"}, func(operation *server.Operation) {
		hub := server.GetRouteHub()
		routes := make([]string, 0)
		for route, _ := range hub.DirectRouter {
			//println(route)
			routes = append(routes, route)
		}
		for route, _ := range hub.RegxRouter {
			//println(route)
			routes = append(routes, route)
		}
		sort.Strings(routes)
		//创建route文件
		existed := register.GetRoutes()

		newRoutes := make(map[string]ez.M)

		//创建文件
		bf := bytes.NewBufferString(`package register
import "gitee.com/dreamwood/ez"
var routes map[string]ez.M
func init() {
	routes = `)
		for _, route := range routes {
			if find, ok := existed[route]; ok {
				newRoutes[route] = find
			} else {
				newRoutes[route] = ez.M{"name": "未定义", "public": 0}
			}
		}
		data := fmt.Sprintf("%#v", newRoutes)
		data = strings.ReplaceAll(data, "},", "},\n")
		bf.WriteString(data)
		bf.WriteString(`
}

func GetRoutes() map[string]ez.M {
	return routes
}`)
		bf.WriteString(`
//这些是本更新后对比上次，移除的内容，请详细核对
var missed = `)
		missedData := make(map[string]ez.M)
		for route, conf := range existed {
			find := false
			for key, _ := range newRoutes {
				if key == route {
					find = true
				}
			}
			if !find {
				missedData[route] = conf
			}
		}
		missed := fmt.Sprintf("%#v", missedData)
		missed = strings.ReplaceAll(missed, "},", "},\n")
		bf.WriteString(missed)
		path := "./config/register/routes.go"
		oldData := ez.ReadFile(path)
		e := os.WriteFile(fmt.Sprintf("./var/logs/routes.go.%s.log", ez.GetDateYMDHIS("", "", "")), oldData, 077)
		ez.PrintError(e)
		e = os.WriteFile(path, bf.Bytes(), 0777)
		ez.PrintError(e)
		e = exec.Command("go", "fmt", path).Run()
		ez.PrintError(e)
	})
}
